<!--
 * @Author: 江沅锋 yuanfeng.jiang@symbio.com.cn
 * @Date: 2024-12-19 15:31:27
 * @LastEditors: 江沅锋 yuanfeng.jiang@symbio.com.cn
 * @LastEditTime: 2024-12-30 10:15:49
 * @FilePath: \snow-frontend-pc\src\views\projects\procurement\centralizedPurchasing\components\associatedItem.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-dialog
    v-model="visible"
    title="关联项目"
    destroy-on-close
    width="1500px"
    @close="handleCancel"
  >
    <div class="dialog" @click.stop="handleDeptList(false)">
      <div class="canChooseBox">
        <div class="title">可选项目</div>
        <div class="tableBox">
          <el-form
            :inline="true"
            :model="formInline"
            ref="formRef"
            class="demo-form-inline"
            size="small"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属片区/工厂">
                  <el-input
                    clearable
                    placeholder="所属片区/工厂"
                    v-model.trim="filterText"
                    @clear="clearInput"
                    class="width-custom"
                    @click.stop="handleDeptList(true)"
                  ></el-input>
                  <el-tree
                    clearable
                    ref="treeRef"
                    class="filter-tree"
                    :data="deptList"
                    default-expand-all
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    v-if="showDeptList"
                    @node-click="handleChangeDept"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目名称/编号" prop="projectNameLike">
                  <el-input
                    clearable
                    class="width-custom"
                    v-model.trim="formInline.projectNameLike"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目年度" prop="projectYear">
                  <el-date-picker
                    v-model="formInline.projectYear"
                    type="year"
                    value-format="YYYY"
                    placeholder="项目年度"
                    class="width-custom"
                    clearable
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item class="btn-wrap" style="float: right">
                  <el-button type="primary" @click="handleSearch">
                    查询
                  </el-button>
                  <el-button @click="handleReset">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-skeleton
            style="height: 330px"
            :rows="8"
            :loading="loading"
            animated
          >
          </el-skeleton>
          <el-table
            :data="tableData"
            stripe
            v-show="!loading"
            style="width: 100%; margin-top: 20px"
            height="330px"
            row-key="id"
            ref="tableRef"
            @selection-change="selectionChange"
            :header-cell-style="{
              background: '#F7F9FD',
              color: '#000',
              height: '48px',
              borderTop: '1px soild #E4E8F2'
            }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="selection"
              :reserve-selection="true"
              :selectable="handleSelectable"
              width="35"
            />
            <el-table-column type="index" label="序号" width="50">
              <template v-slot="scope">
                <span>{{
                  (formInline.pageNum - 1) * formInline.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="项目名称"
              prop="projectName"
              width="230"
            ></el-table-column>
            <el-table-column
              prop="projectCode"
              label="项目编号"
              width="200"
            ></el-table-column>
            <el-table-column
              prop="approvalAmount"
              label="项目立项批准金额(万元)"
              width="200"
            ></el-table-column>
          </el-table>
          <re-pagination
            :total="total"
            v-show="total > 0"
            v-model:page="formInline.pageNum"
            v-model:limit="formInline.pageSize"
            @pagination="handleSearch(formInline.pageNum)"
          />
        </div>
      </div>
      <div class="selectedBox">
        <div class="title">
          <div class="left">已选项目({{ selectData.length }})</div>
          <div class="right">标段金额合计：{{ getSelectMoney }}万元</div>
        </div>
        <div class="tableBox">
          <div class="tableItem" v-for="(i, j) in selectData" :key="j">
            <div class="hideBox" v-if="i.isClose">
              <div class="tableTitle">
                <div class="name" v-if="i.projectLotName">
                  <div class="projectLotName" :title="i.projectLotName">
                    {{ i.projectLotName }}
                  </div>
                  <div class="projectLotAmount">
                    {{ i.projectLotAmount || 0 }} 万元
                  </div>
                </div>
                <div class="name" v-else>
                  <div
                    class="projectName"
                    :title="`【${i.projectCode}】 ${i.projectName}`"
                  >
                    {{ `【${i.projectCode}】 ${i.projectName}` }}
                  </div>
                </div>
                <el-popconfirm
                  title="删除后填写的信息将丢失，确认删除？"
                  @confirm="itemDelete(i)"
                >
                  <template #reference>
                    <div class="delete">
                      <el-icon><Delete /></el-icon>
                    </div>
                  </template>
                </el-popconfirm>
                <div class="closeBtn" @click="i.isClose = !i.isClose">
                  <el-icon><ArrowUpBold /></el-icon>
                  <!-- <el-icon><DArrowRight /></el-icon> -->
                </div>
              </div>
            </div>
            <div class="showBox" v-else>
              <div class="tableTitle">
                <div class="name">
                  {{ `【${i.projectCode}】 ${i.projectName}` }}
                </div>
                <el-popconfirm
                  title="删除后填写的信息将丢失，确认删除？"
                  @confirm="itemDelete(i)"
                >
                  <template #reference>
                    <div class="delete">
                      <el-icon><Delete /></el-icon>
                    </div>
                  </template>
                </el-popconfirm>
                <div class="closeBtn" @click="i.isClose = !i.isClose">
                  <el-icon><ArrowDownBold /></el-icon>
                  <!-- <el-icon><DArrowLeft /></el-icon> -->
                </div>
              </div>
              <div class="projectBox">
                <div class="projectItem">
                  <div class="label"><span>*</span>项目标段名称：</div>
                  <div class="value">
                    <el-input
                      clearable
                      placeholder="请输入"
                      v-model.trim="i.projectLotName"
                    />
                  </div>
                </div>
                <div class="projectItem">
                  <div class="label"><span>*</span>项目标段预算金额：</div>
                  <div class="value">
                    <el-input-number
                      v-model="i.projectLotAmount"
                      placeholder="请输入"
                      :controls="false"
                      precision="6"
                      :min="0"
                      :max="Number(i.approvalAmount)"
                    />
                  </div>
                  <div class="text">
                    万元，立项批准金额：{{ i.approvalAmount }}万元
                  </div>
                </div>
                <div class="projectItem">
                  <div class="label">采购技术方案初审时间：</div>
                  <div class="value">
                    <el-date-picker
                      v-model="i.purchasePlanFirstReviewTime"
                      type="date"
                      placeholder="请选择"
                      clearable
                    />
                  </div>
                </div>
                <div class="projectItem">
                  <div class="label">采购技术方案定稿时间：</div>
                  <div class="value">
                    <el-date-picker
                      v-model="i.purchasePlanFinalVersionTime"
                      type="date"
                      placeholder="请选择"
                      clearable
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="handleSure">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits, computed, watch } from "vue";
import {
  projectLotList,
  getDeptTree,
  alreadyMappingList,
  saveProjectLotMapping
} from "/@/api/projects";
import RePagination from "/@/components/RePagination/index.vue";
import NotifMessage from "/@/utils/message/notification";
const formRef = ref<HTMLFormElement | null>(null) as any;
const tableRef = ref<HTMLElement | null>(null) as any;
const emit = defineEmits(["submit"]);
const formInline = reactive({
  pageNum: 1,
  pageSize: 10,
  projectRegionCode: "",
  projectNameLike: "",
  projectYear: ""
});
const deptList = ref([]);
const selectRows = ref([]);
const selectData = ref([]);
const tableData = ref([]);
const saveData = ref([]);
const filterText = ref("");
const total = ref<number>(0);
const visible = ref(false);
const showDeptList = ref(false);
const loading = ref<boolean>(false);
const btnLoading = ref<boolean>(false);
const defaultProps = ref({
  children: "children",
  label: "deptDescShrt"
});

const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  pitchDetail: {
    type: Object,
    default: () => {}
  }
});
watch(
  () => props.showDialog,
  newVal => {
    visible.value = newVal;
    if (newVal) {
      initData();
    }
  }
);
const initData = () => {
  selectData.value = [];
  getDeptTreeFunc();
  getMappingList();
  formInline.pageNum = 1;
  getTableData(formInline);
};
const getMappingList = async () => {
  const res = (await alreadyMappingList({
    id: props.pitchDetail.id
  })) as any;
  const { code, data } = res;
  if (code === 200) {
    saveData.value = data;
  }
};
const handleSelectable = (row: any) => {
  return !saveData.value.find((val: any) => {
    return val.projectId === row.id;
  });
};
const getTableData = (obj: any) => {
  loading.value = true;
  projectLotList({
    ...obj
  })
    .then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        tableData.value = data.list;
        total.value = data.rows;
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

// 工厂区域
const getDeptTreeFunc = async () => {
  getDeptTree({}).then((res: any) => {
    deptList.value = res.data || [];
  });
};
// 根据条件进行搜索
const handleSearch = (page?: any) => {
  if (!page) {
    formInline.pageNum = 1;
  }
  getTableData(formInline);
};
// 重置条件
const handleReset = () => {
  formRef.value.resetFields();
  formInline.projectRegionCode = "";
  filterText.value = "";
  getTableData(formInline);
};
const filterNode = (value: string, data) => {
  if (!value) return true;
  return data.deptDescShrt.includes(value);
};
const handleDeptList = flag => {
  showDeptList.value = flag;
};
const clearInput = () => {
  formInline.projectRegionCode = "";
};
const handleChangeDept = node => {
  formInline.projectRegionCode = node.id;
  filterText.value = node.deptDescShrt;
  showDeptList.value = false;
};
const handleCancel = () => {
  emit("submit", "cancel");
  handleDeptList(false);
};
const handleSure = () => {
  if (selectData.value.length === 0) {
    NotifMessage.error("请选择要关联的项目");
    return;
  }
  const arr = [];
  const getTime = (time: any) => {
    if (!time) {
      return;
    }
    const timer = time ? new Date(time) : new Date();
    const year = timer.getFullYear();
    const month = timer.getMonth() + 1;
    const date = timer.getDate();
    return `${year}-${month}-${date}`;
  };
  for (let i = 0; i < selectData.value.length; i++) {
    const item = selectData.value[i];
    if (!item.projectLotName) {
      NotifMessage.error(`项目${item.projectName}请输入项目标段名称`);
      return;
    }
    if (!item.projectLotAmount && item.projectLotAmount !== 0) {
      NotifMessage.error(`项目${item.projectName}请输入项目标段预算金额`);
      return;
    }
    arr.push({
      projectLotName: item.projectLotName, //项目标段名称
      projectId: item.id, //项目ID
      projectName: item.projectName, //项目名称
      projectNum: item.projectCode, //项目编号
      approvalAmount: item.approvalAmount, //项目立项批准金额
      purchaseLotId: props.pitchDetail.id, //集采标段ID
      purchaseLotName: props.pitchDetail.purchaseLotName, //集采标段名称
      purchaseLotNum: props.pitchDetail.purchaseLotNum, //集采标段编号
      projectLotAmount: item.projectLotAmount, //项目标段预算金额
      purchasePlanFirstReviewTime: getTime(item.purchasePlanFirstReviewTime), //采购技术方案初审时间
      purchasePlanFinalVersionTime: getTime(item.purchasePlanFinalVersionTime) //采购技术方案定稿时间
    });
  }
  const params = arr;
  btnLoading.value = true;
  saveProjectLotMapping(params)
    .then((res: any) => {
      if (res.code === 200) {
        NotifMessage.success(`操作成功`);
        handleDeptList(false);
        emit("submit", "sure");
      }
    })
    .finally(() => {
      btnLoading.value = false;
    });
};
const selectionChange = (rows: any) => {
  selectRows.value = rows;
  // 过滤取消勾选
  const filterArr = selectData.value.filter((val: any) => {
    return rows.find((v: any) => val.id === v.id);
  });
  // 添加勾选
  const arr = rows.filter((val: any) => {
    return !filterArr.find((v: any) => val.id === v.id);
  });
  arr.forEach((val: any) => {
    filterArr.unshift({
      ...val,
      isClose: false,
      projectLotName: "",
      projectLotAmount: undefined,
      purchasePlanFirstReviewTime: "",
      purchasePlanFinalVersionTime: ""
    });
  });
  selectData.value = filterArr;
};
const getSelectMoney = computed(() => {
  let sum = 0;
  selectData.value.forEach((val: any) => {
    sum += val.projectLotAmount || 0;
  });
  return Number(sum.toFixed(6));
});
const itemDelete = (i: any) => {
  selectData.value = selectData.value.filter((val: any) => {
    return val.id !== i.id;
  });
  selectRows.value = selectRows.value.filter((val: any) => {
    tableRef.value!.toggleRowSelection(val, val.id !== i.id);
    return val.id !== i.id;
  });
};
</script>
<style scoped lang="scss">
.dialog {
  width: 100%;
  height: 600px;
  display: flex;
  border-top: 1px solid #e4e7ed;
  overflow: hidden;
  .width-custom {
    width: 200px !important;
  }
  .canChooseBox,
  .selectedBox {
    display: flex;
    flex-direction: column;
    padding: 20px;
    .title {
      height: 22px;
      line-height: 22px;
      font-size: 16px;
      color: #333333;
      border-left: 5px solid #0073e5;
      text-indent: 4px;
    }
    .tableBox {
      box-sizing: border-box;
      border: 1px solid #d8d8d8;
      box-sizing: border-box;
      padding: 16px;
      margin-top: 13px;
      overflow: auto;
      flex: 1;
    }
  }
  .canChooseBox {
    width: 800px;
  }
  .selectedBox {
    padding: 20px 20px 20px 0;
    flex: 1;
    margin-right: 10px;
    overflow: hidden;
    .title {
      display: flex;
      .left {
        flex: 1;
      }
    }
    .tableItem {
      width: 100%;
      overflow: hidden;
      border: 1px solid #d8d8d8;
      margin-bottom: 16px;
      &:last-child {
        margin: 0;
      }
      .showBox,
      .hideBox {
        width: 100%;
        overflow: hidden;
        .tableTitle {
          width: 100%;
          height: 44px;
          line-height: 22px;
          box-sizing: border-box;
          padding: 13px 17px 9px 14px;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #f5f5f5;
          overflow: hidden;
          .name {
            flex: 1;
            overflow: hidden;
            display: flex;
            .projectLotName,
            .projectName {
              flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .projectLotAmount {
              margin-left: 10px;
            }
          }
          .delete {
            width: 20px;
            height: 20px;
            margin-left: 12px;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          .closeBtn {
            width: 20px;
            height: 20px;
            margin-left: 8px;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
        .projectBox {
          width: 100%;
          box-sizing: border-box;
          padding: 16px 12px;
          .projectItem {
            width: 100%;
            height: 32px;
            line-height: 32px;
            display: flex;
            margin-bottom: 16px;
            &:last-child {
              margin: 0;
            }
            .label {
              width: 160px;
              text-align: right;
              span {
                color: #f53f3f;
              }
            }
            .value {
              flex: 1;
              .el-input,
              .el-input-number,
              .el-date-picker {
                width: 100%;
              }
              .el-input-number::v-deep .el-input__inner {
                text-align: left !important;
              }
              ::v-deep .el-date-editor--date {
                width: 100%;
              }
            }
            .text {
              width: 290px;
            }
          }
        }
      }
    }
  }
  .filter-tree:deep {
    &.el-tree {
      position: absolute;
      top: 36px;
      width: 400px;
      max-height: 226px;
      overflow: auto;
      border: 1px solid #e4e8f2;
      z-index: 10;
    }
  }
}
</style>
